/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
function TreeNode(val, left, right) {
  this.val = (val === undefined ? 0 : val)
  this.left = (left === undefined ? null : left)
  this.right = (right === undefined ? null : right)
}

let t1 = new TreeNode(1, null, new TreeNode(2, new TreeNode(3, null), null))

// 递归实现
var preorderTraversal = function (root) {
  // 根 -> 左 -> 右
  let ans = []

  if (root) {
    // 将当前节点值压入数组
    ans.push(root.val)
    if (root.left) {
      ans = ans.concat(preorderTraversal(root.left))
    }
    if (root.right) {
      ans = ans.concat(preorderTraversal(root.right))
    }
  }
  return ans
};




// 迭代实现
preorderTraversal = function (root) {
  // 实现思路：使用栈的特性，保存上一节点的内容
  let ans = []
  if (root) {


    let stack = [root]


    while (stack.length > 0) {
      let t = stack.pop()
      ans.push(t.val)
      if (t.right) {
        stack.push(t.right)
      }
      if (t.left) {
        stack.push(t.left)
      }
    }
  }

  return ans;
}

preorderTraversal(t1)